<?php

namespace App\Http\Controllers\Purchase;

use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use App\Models\Purchase\PurchaseAgreement;
use App\Http\Validate\Purchase\PurchaseAgreement as PurchasePurchaseAgreement;
use App\Models\Custom\Custom;
use App\Models\Manger\Manger;
use App\Models\Purchase\PurchaseOrder;
use App\Services\Common\SnCode;

/**
 * 采购协议相关
 */
class PurchaseAgreementController extends BaseController
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $type = $request->type ?? 0;
        $isgetall = $request->isgetall ?? 0;
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 4) {
            $manger_id = 0; //查询所有订单
        }
        $list = PurchaseAgreement::getList($request, $this->mangerinfo['cpid'], $manger_id, $type, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 获取详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $info = PurchaseAgreement::with([
            'mangerinfo' => function ($query) {
                $query->select(['id', 'realname', 'username']);
            },
            'custominfo' => function ($query) {
                $query->select(['id', 'company_name']);
            },
            'settlecompany' => function ($query) {
                $query->select(['id', 'settle_no', 'settle_company_name']);
            },

        ])->where([['id', $id], ['cpid', $this->mangerinfo['cpid'], ['manger_id', $this->mangerinfo['id']]]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info' => $info]]);
    }

    /**
     * 新增采购协议
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only([
            'type',
            'pid',
            'purchase_type',
            'sales_manger_id',
            'custom_id',
            'contract_no',
            'steel_attr_company_id',
            'contract_date',
            'weight',
            'settle_model',
            'settle_model_start_time',
            'settle_model_end_time',
            'price',
            'invoice_type',
            'settle_cycle_month',
            'settle_cycle_date',
            'settle_cycle_type',
            'pay_type',
            'pay_cycle',
            'settle_company_id',
            'contract_filepath',
            'contract_filename',
            'remark'
        ]);
        $req_data['settle_cycle_date'] = intval($req_data['settle_cycle_date']);
        $req_data['settle_cycle_month'] = intval($req_data['settle_cycle_month']);
        $req_data['settle_cycle_type'] = intval($req_data['settle_cycle_type']);
        $Validate = new PurchasePurchaseAgreement();
        if (!$Validate->check($req_data)) { //初筛过滤
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        // //根据实际业务判断
        // if (!in_array($req_data['type'], [1, 2, 3])) {
        //     return response()->json(['code' => '001', 'msg' => '参数错误']);
        // }


        if(($req_data['weight']*10)>99999999999999999){
            return response()->json(['code' => '001', 'msg' => '协议量不可超过10万亿吨']);
        }


        //临时锁单支持点价、锁价，年协月协支持后结算、锁价，后结算选时间区间
        if ($req_data['type'] == 3) {
            if (!in_array($req_data['settle_model'], [1, 2])) {
                return response()->json(['code' => '001', 'msg' => '公司集采只支持点价、锁价']);
            }
        } elseif ($req_data['type'] == 4) {
            if (intval($req_data['sales_manger_id']) <= 0) {
                return response()->json(['code' => '001', 'msg' => '请选择正确业务员账号']);
            }
            if (!in_array($req_data['settle_model'], [1, 2])) {
                return response()->json(['code' => '001', 'msg' => '业务自采只支持点价、锁价']);
            }
        } else {
            if (!in_array($req_data['settle_model'], [1, 3])) {
                return response()->json(['code' => '001', 'msg' => '只支持锁价、后结算']);
            }
        }
        //判断供应商是否有效
        $custominfo = Custom::where([['category', 2], ['custom_status', 3], ['id', $req_data['custom_id']], ['cpid', $this->mangerinfo['cpid']], ['manger_id', $this->mangerinfo['id']]])->first();
        if (!$custominfo) {
            return response()->json(['code' => '001', 'msg' => '无效供应商']);
        }
        $prefix = '';
        if ($req_data['type'] == 1) {
            $prefix = 'Y';
        } elseif ($req_data['type'] == 2) {
            $prefix = 'M';
        } elseif ($req_data['type'] == 3) {
            $prefix = 'DC';
        } elseif ($req_data['type'] == 4) {
            $prefix = 'DS';
        }


        $sn_code = SnCode::getSnCode($prefix); //系统随机生成
        $req_data['contract_date'] = strtotime($req_data['contract_date']);

        $req_data['pid'] = $req_data['type'] == 2 ? intval($req_data['pid']) : 0;
        // $req_data['purchase_type'] = $req_data['type'] == 3 ? intval($req_data['purchase_type']) : 0;

        $req_data['sales_manger_id'] = ($req_data['type'] == 4) ? intval($req_data['sales_manger_id']) : 0;


        if ($req_data['sales_manger_id'] > 0) {
            $sales_manger_info = Manger::where(['id' => $req_data['sales_manger_id'], 'cpid' => $this->mangerinfo['cpid']])->first();
            if (!$sales_manger_info) {
                return response()->json(['code' => '001', 'msg' => '请选择正确业务员账号']);
            }
        }


        if ($req_data['contract_date'] <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择正确日期']);
        }
        // if (!in_array($req_data['settle_model'], [1, 2, 3])) {
        //     return response()->json(['code' => '001', 'msg' => '请选择正确结算模式']);
        // }

        // if (!in_array($req_data['invoice_type'], [1, 2])) {
        //     return response()->json(['code' => '001', 'msg' => '请选择正确票据类型']);
        // }

        // if (!in_array($req_data['settle_cycle_date'], [0, 1, 2, 3]) || !in_array($req_data['settle_cycle_month'], [0, 1, 2, 3]) || !in_array($req_data['settle_cycle_type'], [0, 1, 2])) {
        //     return response()->json(['code' => '001', 'msg' => '请选择正确结算周期']);
        // }

        // if (!in_array($req_data['pay_type'], [1, 2, 3])) {
        //     return response()->json(['code' => '001', 'msg' => '请选择正确付款方式']);
        // }
        $settle_model_end_time = isset($req_data['settle_model_end_time']) ? ((strtotime($req_data['settle_model_end_time']) > 0) ? strtotime($req_data['settle_model_end_time']) : intval($req_data['settle_model_end_time'])) : 0;
        $settle_model_start_time = isset($req_data['settle_model_start_time']) ? ((strtotime($req_data['settle_model_start_time']) > 0) ? strtotime($req_data['settle_model_start_time']) : intval($req_data['settle_model_start_time'])) : 0;

        if ($req_data['settle_model'] == 1) {
            $req_data['settle_model_start_time'] = 0;
            $req_data['settle_model_end_time'] = time();
        }

        if ($req_data['settle_model'] == 2) {

            $req_data['settle_model_start_time'] = 0;
            if ($settle_model_end_time > time()) {
                $req_data['settle_model_end_time'] = $settle_model_end_time;
            } else {
                return response()->json(['code' => '001', 'msg' => '点价模式日期需大于当前时间']);
            }
        }

        if ($req_data['settle_model'] == 3) {
            if ($req_data['settle_model_start_time'] < 0 || $req_data['settle_model_end_time'] < 0) {
                return response()->json(['code' => '001', 'msg' => '后结算模式需选择时间范围']);
            }
            $req_data['settle_model_end_time'] = $settle_model_end_time;
            $req_data['settle_model_start_time'] = $settle_model_start_time;
        }

        $req_data['price'] = (isset($req_data['price']) && $req_data['price'] > 0) ? $req_data['price'] : 0;
        if (($req_data['settle_model'] == 1 || $req_data['settle_model'] == 2) && $req_data['price'] <= 0) {
            return response()->json(['code' => '001', 'msg' => '选择点价和锁价的时候单价必填']);
        }



        $isexist = PurchaseAgreement::where([['cpid', $this->mangerinfo['cpid']], ['contract_no', $req_data['contract_no']]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '合同编号不允许重复']);
        }

        foreach ($req_data as $key => $val) {
            if ($val === '' || $val === null) {
                unset($req_data[$key]);
            }
        }

        $data = $req_data;
        $data['manger_id'] = $this->mangerinfo['id'];
        $data['sn_code'] = $sn_code;
        $data['cpid'] = $this->mangerinfo['cpid'];
        $data['create_at'] = time();
        $data['update_at'] = time();
        $data['weight'] = mathfuncweight('mul', $data['weight'], 10, 0);
        PurchaseAgreement::create($data)->id;
        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 编辑协议
     */
    public function dopostedit(Request $request)
    {
        $id = $request->id ?? 0;
        $info = PurchaseAgreement::where([['id', $id], ['cpid', $this->mangerinfo['cpid']], ['manger_id', $this->mangerinfo['id']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }




        $req_data = $request->only([
            'type',
            'pid',
            'purchase_type',
            'sales_manger_id',
            'custom_id',
            'contract_no',
            'steel_attr_company_id',
            'contract_date',
            'weight',
            'settle_model',
            'settle_model_start_time',
            'settle_model_end_time',
            'price',
            'invoice_type',
            'settle_cycle_month',
            'settle_cycle_date',
            'settle_cycle_type',
            'pay_type',
            'pay_cycle',
            'settle_company_id',
            'contract_filepath',
            'contract_filename',
            'remark'
        ]);
        $Validate = new PurchasePurchaseAgreement();
        if (!$Validate->check($req_data)) { //初筛过滤
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        // //根据实际业务判断
        // if (!in_array($req_data['type'], [1, 2, 3])) {
        //     return response()->json(['code' => '001', 'msg' => '参数错误']);
        // }
        if(($req_data['weight']*10)>99999999999999999){
            return response()->json(['code' => '001', 'msg' => '协议量不可超过10万亿吨']);
        }

        if ($req_data['type'] == 3) {
            if (!in_array($req_data['settle_model'], [1, 2])) {
                return response()->json(['code' => '001', 'msg' => '公司集采只支持点价、锁价']);
            }
        } elseif ($req_data['type'] == 4) {
            if (intval($req_data['sales_manger_id']) <= 0) {
                return response()->json(['code' => '001', 'msg' => '请选择正确业务员账号']);
            }
            if (!in_array($req_data['settle_model'], [1, 2])) {
                return response()->json(['code' => '001', 'msg' => '业务自采只支持点价、锁价']);
            }
        } else {
            if (!in_array($req_data['settle_model'], [1, 3])) {
                return response()->json(['code' => '001', 'msg' => '只支持锁价、后结算']);
            }
        }
        //判断供应商是否有效

        $custominfo = Custom::where([['category', 2], ['custom_status', 3], ['id', $req_data['custom_id']], ['cpid', $this->mangerinfo['cpid']], ['manger_id', $this->mangerinfo['id']]])->first();
        if (!$custominfo) {
            return response()->json(['code' => '001', 'msg' => '无效供应商']);
        }

        $req_data['contract_date'] = strtotime($req_data['contract_date']);

        $req_data['pid'] = $req_data['type'] == 2 ? intval($req_data['pid']) : 0;
        // $req_data['purchase_type'] = $req_data['type'] == 3 ? intval($req_data['purchase_type']) : 0;
        $req_data['sales_manger_id'] = ($req_data['type'] == 4) ? intval($req_data['sales_manger_id']) : 0;

        if ($req_data['sales_manger_id'] > 0) {
            $sales_manger_info = Manger::where(['id' => $req_data['sales_manger_id'], 'cpid' => $this->mangerinfo['cpid']])->first();
            if (!$sales_manger_info) {
                return response()->json(['code' => '001', 'msg' => '请选择正确业务员账号']);
            }
        }
        $req_data['settle_cycle_date'] = intval($req_data['settle_cycle_date']);
        $req_data['settle_cycle_month'] = intval($req_data['settle_cycle_month']);
        $req_data['settle_cycle_type'] = intval($req_data['settle_cycle_type']);

        if ($req_data['contract_date'] <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择正确日期']);
        }
        // if (!in_array($req_data['settle_model'], [1, 2, 3])) {
        //     return response()->json(['code' => '001', 'msg' => '请选择正确结算模式']);
        // }

        // if (!in_array($req_data['invoice_type'], [1, 2])) {
        //     return response()->json(['code' => '001', 'msg' => '请选择正确票据类型']);
        // }

        // if (!in_array($req_data['settle_cycle_date'], [0, 1, 2, 3]) || !in_array($req_data['settle_cycle_month'], [0, 1, 2, 3]) || !in_array($req_data['settle_cycle_type'], [0, 1, 2])) {
        //     return response()->json(['code' => '001', 'msg' => '请选择正确结算周期']);
        // }

        // if (!in_array($req_data['pay_type'], [1, 2, 3])) {
        //     return response()->json(['code' => '001', 'msg' => '请选择正确付款方式']);
        // }
        $settle_model_end_time = isset($req_data['settle_model_end_time']) ? ((strtotime($req_data['settle_model_end_time']) > 0) ? strtotime($req_data['settle_model_end_time']) : intval($req_data['settle_model_end_time'])) : 0;
        $settle_model_start_time = isset($req_data['settle_model_start_time']) ? ((strtotime($req_data['settle_model_start_time']) > 0) ? strtotime($req_data['settle_model_start_time']) : intval($req_data['settle_model_start_time'])) : 0;

        if ($req_data['settle_model'] == 1) {
            $req_data['settle_model_start_time'] = 0;
            $req_data['settle_model_end_time'] = time();
        }

        if ($req_data['settle_model'] == 2) {

            $req_data['settle_model_start_time'] = 0;
            if ($settle_model_end_time > time()) {
                $req_data['settle_model_end_time'] = $settle_model_end_time;
            } else {
                return response()->json(['code' => '001', 'msg' => '点价模式日期需大于当前时间']);
            }
        }

        if ($req_data['settle_model'] == 3) {
            if ($req_data['settle_model_start_time'] < 0 || $req_data['settle_model_end_time'] < 0) {
                return response()->json(['code' => '001', 'msg' => '后结算模式需选择时间范围']);
            }
            $req_data['settle_model_end_time'] = $settle_model_end_time;
            $req_data['settle_model_start_time'] = $settle_model_start_time;
        }


        $req_data['price'] = (isset($req_data['price']) && $req_data['price'] > 0) ? $req_data['price'] : 0;
        if (($req_data['settle_model'] == 1 || $req_data['settle_model'] == 2) && $req_data['price'] <= 0) {
            return response()->json(['code' => '001', 'msg' => '选择点价和锁价的时候单价必填']);
        }

        //判断是否使用
        $is_used = PurchaseOrder::where(['pa_id' => $id, 'is_del' => 1])->count();
        if ($is_used > 0) {
            return response()->json(['code' => '001', 'msg' => '存在订单使用该协议，不可编辑']);
        }
        if ($info->type == 1) {
            //需判断是否存在关联月协议
            $pa_list = PurchaseAgreement::where([['pid', $id], ['cpid', $this->mangerinfo['cpid']]])->pluck('id');
            if (count($pa_list) > 0) {
                $is_used = PurchaseOrder::where(['cpid' => $this->mangerinfo['cpid'], 'is_del' => 1])->whereIn('pa_id', $pa_list)->count(); //查询月协议是否被使用
                if ($is_used > 0) {
                    return response()->json(['code' => '001', 'msg' => '存在订单使用该协议，不可编辑']);
                }
            }
        }

        $isexist = PurchaseAgreement::where([['id', '<>', $id], ['cpid', $this->mangerinfo['cpid']], ['contract_no', $req_data['contract_no']]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '合同编号不允许重复']);
        }

        foreach ($req_data as $key => $val) {
            if ($val === '' || $val === null) {
                unset($req_data[$key]);
            }
        }

        $data = $req_data;
        $data['weight'] = mathfuncweight('mul', $data['weight'], 10, 0);
        $data['update_at'] = time();
        PurchaseAgreement::where([['id', $id], ['cpid', $this->mangerinfo['cpid']], ['manger_id', $this->mangerinfo['id']]])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 删除协议
     */
    public function dodel(Request $request)
    {
        $id = $request->id ?? 0;
        $info = PurchaseAgreement::where([['id', $id], ['cpid', $this->mangerinfo['cpid']], ['manger_id', $this->mangerinfo['id']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        //判断是否使用
        $is_used = PurchaseOrder::where(['pa_id' => $id, 'is_del' => 1])->count();
        if ($is_used > 0) {
            return response()->json(['code' => '001', 'msg' => '存在订单使用该协议，不可删除']);
        }
        if ($info->type == 1) {
            //需判断是否存在关联月协议
            $pa_list = PurchaseAgreement::where([['pid', $id], ['cpid', $this->mangerinfo['cpid']]])->pluck('id');
            if (count($pa_list) > 0) {
                $is_used = PurchaseOrder::where(['cpid' => $this->mangerinfo['cpid'], 'is_del' => 1])->whereIn('pa_id', $pa_list)->count(); //查询月协议是否被使用
                if ($is_used > 0) {
                    return response()->json(['code' => '001', 'msg' => '存在订单使用该协议，不可删除']);
                }
            }
            PurchaseAgreement::where([['pid', $id], ['cpid', $this->mangerinfo['cpid']]])->delete(); //删除月协议
        }

        PurchaseAgreement::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->delete();

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}
